package com.example.weiwing.Loginmain;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.weiwing.R;
import com.example.weiwing.config.WeiWingConfig;
import com.example.weiwing.home.HomeActivity;
import com.example.weiwing.util.OnSwipeTouchListener;

import com.example.weiwing.util.SpUtils;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;

import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class Login extends AppCompatActivity implements View.OnClickListener {
    ImageView imageView;
    TextView textView;
    int count = 0;
    private EditText et_username;
    private EditText et_password;

    private static final int MY_PERMISSION_REQUEST_CODE = 10000;

    public static Context context;

    public Handler mHandler;


    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        context = this;
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);
        imageView = findViewById(R.id.imageView);
        textView = findViewById(R.id.textView);
        et_username = findViewById(R.id.et_username);
        et_password = findViewById(R.id.et_password);
        findViewById(R.id.btn_login).setOnClickListener(this);
        findViewById(R.id.btn_regist).setOnClickListener(this);

        boolean isAllGranted = checkPermissionAllGranted(
                new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.INTERNET,
                        Manifest.permission.CAMERA
                }
        );

        if (!isAllGranted) {
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.INTERNET,
                            Manifest.permission.CAMERA
                    },
                    MY_PERMISSION_REQUEST_CODE
            );
        }

        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);

                if (msg.what == 1) {
                    JSONObject jsonObject = (JSONObject) msg.obj;
                    if (jsonObject.getInteger("code") == 200) {
                        String token = jsonObject.getString("token");
                        String rmsg = jsonObject.getString("msg");
                        SpUtils.putString(Login.this,"token",token);
                        Toast.makeText(Login.this, rmsg, Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(Login.this, HomeActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    } else if (jsonObject.getInteger("code") == 500) {
                        // 登录失败
                        String rmsg = jsonObject.getString("msg");
                        Toast.makeText(Login.this, rmsg, Toast.LENGTH_SHORT).show();
                    }

                }

            }
        };


        imageView.setOnTouchListener(new OnSwipeTouchListener(getApplicationContext()) {

            @SuppressLint("SetTextI18n")
            public void onSwipeRight() {
                if (count == 0) {
                    imageView.setImageResource(R.drawable.good_night_img);
                    textView.setText("Night");
                    count = 1;
                } else {
                    imageView.setImageResource(R.drawable.good_morning_img);
                    textView.setText("Morning");
                    count = 0;
                }
            }

            public void onSwipeTop() {
            }

            @SuppressLint("SetTextI18n")
            public void onSwipeLeft() {
                if (count == 0) {
                    imageView.setImageResource(R.drawable.good_night_img);
                    textView.setText("Night");
                    count = 1;
                } else {
                    imageView.setImageResource(R.drawable.good_morning_img);
                    textView.setText("Morning");
                    count = 0;
                }
            }

            public void onSwipeBottom() {
            }

        });


    }

    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                return false;
            }
        }
        return true;
    }

    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.tv_forget_password) {
            // TODO: 跳转到忘记密码页面
        } else if (view.getId() == R.id.btn_regist) {
            Intent it = new Intent(this, LoginEdit.class);
            startActivity(it);
        } else if (view.getId() == R.id.btn_login) {
            // 登录逻辑
            String username = et_username.getText().toString();
            String password = et_password.getText().toString();
            // 校验username password 合法性
            if (username.length() < 5 || username.length() > 18) {
                Toast.makeText(this, "用户名长度在5-18之间", Toast.LENGTH_SHORT).show();
                return;
            }

            if (password.length() < 6 || password.length() > 18) {
                Toast.makeText(this, "密码长度在6-18之间", Toast.LENGTH_SHORT).show();
                return;
            }

            new Thread(() -> {
                try {
                    HttpRequest.JSONPOST(context, WeiWingConfig.getUrl() + "/user/login", "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}", new ResponseListener() {
                        @Override
                        public void onResponse(String response, Exception error) {
                            if (error == null) {

                                JSONObject jsonObject = JSON.parseObject(response);

                                mHandler.obtainMessage(1, jsonObject).sendToTarget();

                            } else {

                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();


        }


    }


}